<template>
    <el-cascader :clearable="props.clearable"  v-model="buildingId" :options="buildingList" :props="buildingProps" @change="handleChange" />
</template>
<script setup lang='ts'>
import { getBuildingList } from '@/apis/building/building';
import { BuildingNode } from '@/apis/building/type';
import { ref, defineProps, onMounted, defineModel,defineEmits } from 'vue';

const emit=defineEmits(["change"]);

 const buildingId=  defineModel();

const props = withDefaults(defineProps<{ type: string | undefined,clearable:boolean }>(), {
    type: undefined,
    clearable:false
})

const buildingProps = {
    label: 'name',
    value: 'id',
    checkStrictly: false,
    multiple: false,
}

switch (props.type) {
    case undefined:
        buildingProps.checkStrictly = false;
        break;
    case "single":
        buildingProps.checkStrictly = true;
        break;
    case "multiple":
        buildingProps.checkStrictly = true;
        buildingProps.multiple = true;
        break;
    default:
        break;
}

const buildingList = ref<BuildingNode[]>([]);
const getBuildingData = async () => {

    const res = await getBuildingList();
    buildingList.value = res.data.list;

}
const handleChange = (data: any) => {

    let values: number[] | number | undefined;

    if (!data) {

        values = undefined;
    }
    else {

        switch (props.type) {
            case undefined:
            case "single":
                values = data[data.length - 1];
                break;
            case "multiple":
                // let ids: number[] = [];
                // value.forEach((item: number[]) => {
                //     item.forEach((item2: number) => {
                //         ids.push(item2);
                //     })
                // })
                // values = [...new Set(ids)];
                values=[...new Set(data.flat())] as number[];
                break;
            default:
                break;
        }

    }

    console.log("得到选中的数据", values)
    buildingId.value=values;

    emit("change",values)

}
onMounted(() => {
    getBuildingData();

})

</script>
<style scoped lang='less'></style>